#!/bin/bash

# Color
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'


# Make sure only root can run our script
[[ $EUID -ne 0 ]] && echo -e "[${red}Error${plain}] This script must be run as root!" && exit 1

versions=(
'JDK5'
'JDK6'
'JDK7'
'JDK8'
)


# select jdk version
while true
do
echo -e "Please select version:"
for ((i=1;i<=${#versions[@]};i++ )); do
        hint="${versions[$i-1]}"
        echo -e "${green}${i}${plain}) ${hint}"
    done
read -p "Which version you'd select(Default: ${versions[0]}):" pick
    [ -z "$pick" ] && pick=1
    expr ${pick} + 1 &>/dev/null
    if [ $? -ne 0 ]; then
        echo -e "[${red}Error${plain}] Please enter a number"
        continue
    fi
    if [[ "$pick" -lt 1 || "$pick" -gt ${#versions[@]} ]]; then
        echo -e "[${red}Error${plain}] Please enter a number between 1 and ${#versions[@]}"
        continue
    fi
    version=${versions[$pick-1]}
    echo
    echo "---------------------------"
    echo "version = ${version}"
    echo "---------------------------"
    echo
break
done

# select install path
echo -e "Please type instlal path:"
read -p "Please type instlal path(Default: /opt/$version):" path
[ -z "$path" ] && path="/opt/$version"
cd ${path} &>/dev/null
if [ $? -ne 0 ]; then
    mkdir $path &>/dev/null
fi
echo
echo "---------------------------"
echo "install path = ${path}"
echo "---------------------------"
echo


echo -e "${green}java $version installing...${plain}"
case $version in 
'JDK5')
suffix='.bin'
javahome="$path/jdk1.5.0_22"
url='http://35.187.255.97/jdk-1_5_0_22-linux-amd64.bin'
;;
'JDK6')
url='http://35.187.255.97/jdk-6u45-linux-x64.bin'
suffix='.bin'
javahome="$path/jdk1.6.0_45"
;;
'JDK7')
url='http://35.187.255.97/jdk-7u80-linux-x64.tar.gz'
suffix='.tar.gz'
javahome="$path/jdk1.7.0_80"
;;
'JDK8')
url='http://35.187.255.97/jdk-8u181-linux-x64.tar.gz'
suffix='.tar.gz'
javahome="$path/jdk1.8.0_181"
;;
esac
#echo $path
#cd $path
#echo $url
#echo "$path/$version$suffix"
fullpath="$path/$version$suffix"
if [ ! -f $fullpath ];
then
 wget $url -O $fullpath
fi

cd $path

case $suffix in
'.bin')
 if [ ! -d $javahome ];
 then
 sh $fullpath
 fi
;;
'.tar.gz')
 if [ ! -d $javahome ];
 then
 tar -zxvf $fullpath
 fi
;;
esac


#set environmental variable of java
`sed -i '/export JAVA_HOME/d' ~/.bashrc`
`sed -i '$a\'"export JAVA_HOME=$javahome" ~/.bashrc`
`sed -i '/export JRE_HOME/d' ~/.bashrc`
`sed -i '$a\export JRE_HOME=$JAVA_HOME/jre' ~/.bashrc`
`sed -i '/export CLASSPATH/d' ~/.bashrc`
`sed -i '$a\export CLASSPATH=.:$JAVA_HOME/lib:$JRE_HOME/lib:$CLASSPATH' ~/.bashrc`
`sed -i '/export PATH=$JAVA_HOME\/bin/d' ~/.bashrc`
`sed -i '$a\export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH' ~/.bashrc`
source ~/.bashrc
java -version
if [ $? -ne 0 ];
then
 echo -e "[${red}Error${plain}] faild to install java $version"
fi
#apt-get remove -y  java*
#apt purge `dpkg -l | grep java| awk '{print $2}' |tr "\n" " "`
#dpkg --get-selections | grep java |xargs apt-get autoremove
